package cn.zhaoyun.service.impl;

import cn.zhaoyun.dao.EmpDao;
import cn.zhaoyun.entity.Emp;
import cn.zhaoyun.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
// 如果有多个缓存管理器, 可通过 cacheManager 属性进行选择
// 也可以在方法上设定
@Cacheable(cacheNames = "emps"/*, cacheManager = "redisCacheManager"*/)
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpDao dao;

    @Override
    @Transactional(readOnly = true)
    // 缓存组件名称: emps
    // 缓存 key: 参数 id 的值
    // unless: 如果结果为 null 则不进行缓存
    @Cacheable(/*cacheNames = "emps",*/ key = "#id", unless = "#result == null")
    public Emp findById(long id) {
        System.out.println("service执行操作, 根据id查询员工: " + id);
        return dao.selectById(id);
    }

    @Override
    @CachePut(/*cacheNames = "emps",*/ key = "#emp.id")
    public Emp update(Emp emp) {
        System.out.println("service执行操作, 更新员工信息: " + emp);
        dao.update(emp);
        return emp;
    }

    @Override
    @CacheEvict(/*cacheNames = "emps",*/ key = "#id")
    public void delete(long id) {
        System.out.println("service执行操作, 删除员工: " + id);
        // dao.deleteById(id);
    }

    @Override
    @Caching(cacheable = {
            // 根据员工姓名做一份组成
            @Cacheable(/*cacheNames = "emps",*/ key = "#name")
    }, put = {
            // 根据查询结果的员工id也做一份缓存, 但如果结果为null不做缓存
            // 由于在缓存规则中使用了@CachePut, 目标方法是一定会被执行的
            @CachePut(/*cacheNames = "emps",*/ key = "#result.id", unless = "#result == null")
    }, evict = {
            // 如果查询结果为null, 进行缓存清空操作
            @CacheEvict(/*cacheNames = "emps",*/ key = "#name", condition = "#result == null")
    })
    public Emp findByName(String name) {
        System.out.println("service执行操作, 根据姓名查询员工: " + name);
        return dao.selectByName(name);
    }
}
